//
//  HNSH_GroupManageViewController.m
//  HNSH_SingleProject
//
//  Created by 李宇廷 on 2023/2/18.
//

#import "HNSH_GroupManageViewController.h"

//model
#import "HNSH_GroupInfoModel.h"
#import "HNSH_ChatFriendModel.h"

//view
#import "HNSH_GroupChatInfoCommonCell.h"
#import "HNSH_GroupManageSwitchCell.h"
#import "HNSH_GroupChatInfoSwitchCell.h"
#import "HNSH_GroupManageFooterView.h"

//vc
#import "HNSH_GroupApplyViewController.h"           //邀请进群申请
#import "HNSH_GroupAdminListViewController.h"       //群管理员

@interface HNSH_GroupManageViewController ()
/** */
@property (nonatomic, copy)NSArray <NSArray *> * dataArray;
/** */
@property (nonatomic, strong)HNSH_GroupInfoUserModel * groupModel;
/** */
@property (nonatomic, copy)NSArray * membersArray;
@end

static NSString *HNSH_GroupChatInfoCommonCellID = @"HNSH_GroupChatInfoCommonCellID";
static NSString *HNSH_GroupManageSwitchCellID = @"HNSH_GroupManageSwitchCellID";
static NSString *HNSH_GroupManageFooterViewID = @"HNSH_GroupManageFooterViewID";
static NSString *UICollectionReusableViewID = @"UICollectionReusableViewID";
static NSString *HNSH_GroupChatInfoSwitchCellID = @"HNSH_GroupChatInfoSwitchCellID";

@implementation HNSH_GroupManageViewController

//MARK: Cycle Methods
- (void)viewDidLoad{
    [super viewDidLoad];
        
    [self showNavTitle:@"群管理" showLeftItem:YES];
    
    [self addAllViews];
    
    [self configCollectionView];
    
    [self setDefaultData];
        
    [self loadGroupInfo];
    
    [self loadMembersData];
}

- (void)configCollectionView {
    [self.collectionView registerClass:[HNSH_GroupManageSwitchCell class] forCellWithReuseIdentifier:HNSH_GroupManageSwitchCellID];
    [self.collectionView registerClass:[HNSH_GroupChatInfoCommonCell class] forCellWithReuseIdentifier:HNSH_GroupChatInfoCommonCellID];
    [self.collectionView registerClass:[HNSH_GroupChatInfoSwitchCell class] forCellWithReuseIdentifier:HNSH_GroupChatInfoSwitchCellID];
    [self.collectionView registerClass:[HNSH_GroupManageFooterView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:HNSH_GroupManageFooterViewID];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:UICollectionReusableViewID];
}

- (void)loadMembersData{
    [HNSH_ChatNetServer requestRongCloudGroupMembersWithGroupId:self.targetId success:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            NSArray * data = responseObject.resultset;
            self.membersArray = [NSArray yy_modelArrayWithClass:HNSH_ChatFriendModel.class json:data];
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

//MARK: Myself Methods
- (void)addAllViews{
    [self.view addSubview:self.collectionView];
}

- (void)loadGroupInfo{
    [HNSH_ChatNetServer requestRongCloudGroupInfoWithGroupId:self.targetId success:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            NSDictionary * data = responseObject.resultset;
            RCGroup * group = [[RCGroup alloc] init];
            group.groupId = data[@"encode_id"];
            NSString * displayName = data[@"display_name"];
            group.groupName = displayName.length ? displayName : data[@"name"];
            group.portraitUri = data[@"portrait_url"];
            [[RCIM sharedRCIM] refreshGroupInfoCache:group withGroupId:self.targetId];
            
            HNSH_GroupInfoUserModel * model = [HNSH_GroupInfoUserModel yy_modelWithDictionary:data];
            self.groupModel = model;
            [self setDefaultData];
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

//
- (void)setDefaultData{
    BOOL mute = self.groupModel.verify_status;
    BOOL forbid = self.groupModel.rename_status;
    self.dataArray = @[
        @[@{@"title":@"群聊邀请确认", @"des":@"启用后，群成员需群主或群管理员确认才能邀请朋友进群，扫描二维码进群将同时停用", @"isOn":@(mute)}],
        @[@{@"title":@"仅群主/管理员可修改群聊名称", @"des":@"", @"isOn":@(forbid)}],
        @[@{@"title":@"邀请进群申请"}],
        @[@{@"title":@"群管理员"}]
    ];
    [self.collectionView reloadData];
}

//MARK: 修改开关状态
- (void)switchViewAction:(UISwitch *)sender{
    HNSH_GroupChatInfoCommonCell * cell = (HNSH_GroupChatInfoCommonCell *)sender.superview.superview;
    NSIndexPath * indexPath = [self.collectionView indexPathForCell:cell];
    if (indexPath.section == 0) {
        //设置禁言
        [self setMuteWithSender:sender];
    }
    if (indexPath.section == 1) {
        [self setBFWithSender:sender];
    }
}

//群状态切换  1:邀请确认开关 2:群聊名称开关
- (void)setMuteWithSender:(UISwitch *)switchView{
    [HNSH_ChatNetServer requestRongCloudGroupSwitchStatusWithGroupId:self.targetId switch_type:1 success:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            [self.view makeToast:@"修改成功"];
            self.groupModel.verify_status = !self.groupModel.verify_status;
            [self setDefaultData];
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

//群状态切换  1:邀请确认开关 2:群聊名称开关
- (void)setBFWithSender:(UISwitch *)switchView{
    [HNSH_ChatNetServer requestRongCloudGroupSwitchStatusWithGroupId:self.targetId switch_type:2 success:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            [self.view makeToast:@"修改成功"];
            self.groupModel.rename_status = !self.groupModel.rename_status;
            [self setDefaultData];
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

- (void)delete{
    WeakSelf(weakSelf);
    [HNSH_AlertView showTitle:@"确定要解散该群聊吗？" des:@"" buttonTitle:@"解散" buttonColor:[UIColor appGreenColor] buttonClick:^{
        [weakSelf levea];
    }];
}

- (void)clear{
    [[RCIMClient sharedRCIMClient] clearHistoryMessages:ConversationType_GROUP targetId:self.targetId recordTime:[NSString getNowTimeTimestamp].longLongValue clearRemote:YES success:^{
        
    } error:^(RCErrorCode status) {
            
    }];
}

- (void)levea{
    [HNSH_ChatNetServer requestRongCloudGroupDismissWithGroupId:self.targetId success:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            [kSTWindow makeToast:@"解散成功"];
            [self clear];
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}


//MARK: UICollectionViewDelegate Methods
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return self.dataArray.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArray[section].count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        HNSH_GroupManageSwitchCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:HNSH_GroupManageSwitchCellID forIndexPath:indexPath];
        cell.dic = self.dataArray[indexPath.section][indexPath.row];
        [cell.switchView addTarget:self action:@selector(switchViewAction:) forControlEvents:UIControlEventValueChanged];
        return cell;
    } else if (indexPath.section == 1) {
        HNSH_GroupChatInfoSwitchCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:HNSH_GroupChatInfoSwitchCellID forIndexPath:indexPath];
        cell.dic = self.dataArray[indexPath.section][indexPath.row];
        cell.switchView.hidden = NO;
        cell.openButton.hidden = YES;
        [cell.switchView addTarget:self action:@selector(switchViewAction:) forControlEvents:UIControlEventValueChanged];
        return cell;
    } else {
        HNSH_GroupChatInfoCommonCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:HNSH_GroupChatInfoCommonCellID forIndexPath:indexPath];
        cell.backgroundColor = [UIColor appWhiteLabelColor];
        cell.dic = self.dataArray[indexPath.section][indexPath.row];
        return cell;
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return CGSizeMake(kScreenWidth, 90);
    } else {
        return CGSizeMake(kScreenWidth, 52);
    }
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if (kind == UICollectionElementKindSectionFooter) {
        if (indexPath.section == self.dataArray.count - 1) {
            HNSH_GroupManageFooterView * view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:HNSH_GroupManageFooterViewID forIndexPath:indexPath];
            WeakSelf(weakSelf);
            view.deleteBlock = ^{
                [weakSelf delete];
            };
            return view;
        } else {
            UICollectionReusableView * view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:UICollectionReusableViewID forIndexPath:indexPath];
            view.backgroundColor = [UIColor appBGColor];
            return view;
        }
    }
    return nil;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeZero;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    if (section == self.dataArray.count - 1) {
        return CGSizeMake(kScreenWidth, 8 + 50);
    } else {
        if (section == 0 || section == 1) {
            return CGSizeMake(kScreenWidth, 8);
        }
    }
    return CGSizeZero;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 2) {
        HNSH_GroupApplyViewController * vc = [HNSH_GroupApplyViewController new];
        vc.targetId = self.targetId;
        [self.navigationController pushViewController:vc animated:YES];
    }
    if (indexPath.section == 3) {
        HNSH_GroupAdminListViewController * vc = [HNSH_GroupAdminListViewController new];
        vc.targetId = self.targetId;
        vc.membersArray = self.membersArray;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

@end
